package com.renjibo.childred.fragments;


import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabWidget;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.views.MyListView;
import com.renjibo.childred.MainActivity;
import com.renjibo.childred.R;
import com.renjibo.childred.modle.HomeItemBean;
import com.renjibo.childred.utils.PostHead;
import com.renjibo.childred.views.TextViewImage;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends Fragment implements View.OnClickListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String image[] = {"http://dl.bizhi.sogou.com/images/1440x900/2014/08/21/827546.jpg", "http://img04.sogoucdn.com/app/a/100520093/2ad11b094c93197d-4afaf786506af54b-9fd277aea03c8387ebd35dcfba4ba3dd.jpg",
            "http://blog.cntv.cn/attachments/simg/201204/01/a01cccf40d6834bced444c461e7ecdff.jpg", "http://www.fzlimg.com/d/file/036/201001251804161144.jpg",
            "http://i4.3conline.com/images/piclib/201101/27/batch/1/82869/1296117944310c6ojarzzr1.jpg"};
    private List<ImageView> imageArray = new ArrayList<>();
    private String mParam1;
    private String mParam2;
    private MyListView myView;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int currentItem = home_viewPager.getCurrentItem();
            currentItem++;
            home_viewPager.setCurrentItem(currentItem);
            mHandler.sendEmptyMessageDelayed(1, 2000);
        }
    };
    private ViewPager home_viewPager;
    private LinearLayout home_bottom_linear;
    private Gson gson;
    private List<HomeItemBean.HomeBannerBean> home_bannerArray = new ArrayList<>();
    private TextViewImage home_holder;
    private TextViewImage home_xinpin;
    private TextViewImage home_cuxiao;
    private TextViewImage home_qianggou;
    private TextViewImage home_tuijian;
    private ScareTimeFragment scareTimeFragment;
    private LookForFragment lookForFragment;
    private EditText home_editText;
    private ImageView home_imageView_scan;
    private TabWidget tabWidget;

    public HomeFragment() {

    }


    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

//        Log.d("zzz","Home onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        gson = new Gson();
        scareTimeFragment = ScareTimeFragment.newInstance("", "");
        lookForFragment = LookForFragment.newInstance("", "");
//        Log.d("zzz","Home onCreate");
    }

    /**
     * 修改小圆点
     *
     * @param postion
     */
    public void setImagSrc(int postion) {
//        Log.d("zzz","Home setImagSrc");
        for (int i = 0; i < imageArray.size(); i++) {
            if (i == postion) {//xuan zhong
//                Log.d("zzz","Home setImagSrc true");
                imageArray.get(i).setImageResource(R.drawable.cicle_image);
            } else {
//                Log.d("zzz","Home setImagSrc false");
                imageArray.get(i).setImageResource(R.drawable.cicle_image_sleect);
            }
        }
    }

    public void getHomeJson(String url) {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
//        Log.d("zzz","Home onCreateView");
        initView(view);

        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("zzz","Home onPause");
        mHandler.removeMessages(1);
    }

    @Override
    public void onResume() {
        super.onResume();
//        Log.d("zzz","Home onResume");
        tabWidget = (TabWidget) getActivity().findViewById(android.R.id.tabs);
        tabWidget.setVisibility(View.VISIBLE);
//        mHandler.removeMessages(1);
//        mHandler.sendEmptyMessageDelayed(1, 2000);
    }

    public void initView(View view) {
        home_viewPager = (ViewPager) view.findViewById(R.id.home_viewPager);
        home_imageView_scan = (ImageView) view.findViewById(R.id.home_imageView_scan);
        RelativeLayout relatiOne = (RelativeLayout) view.findViewById(R.id.relati);
        home_bottom_linear = (LinearLayout) view.findViewById(R.id.home_bottom_linear);
        home_editText = (EditText) view.findViewById(R.id.home_editText);
        //
        home_holder = (TextViewImage) view.findViewById(R.id.home_holder);
        home_xinpin = (TextViewImage) view.findViewById(R.id.home_xinpin);
        home_cuxiao = (TextViewImage) view.findViewById(R.id.home_cuxiao);
        home_qianggou = (TextViewImage) view.findViewById(R.id.home_qianggou);
        home_tuijian = (TextViewImage) view.findViewById(R.id.home_tuijian);
        //
        home_imageView_scan.setOnClickListener(this);
        home_editText.setOnClickListener(this);
        home_holder.setOnClickListener(this);
        home_xinpin.setOnClickListener(this);
        home_cuxiao.setOnClickListener(this);
        home_qianggou.setOnClickListener(this);
        home_tuijian.setOnClickListener(this);
        //
        imageArray.clear();
        for (int i = 0; i < image.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(30, 30));
            if (i == 0) {
                imageView.setImageResource(R.drawable.cicle_image);
            } else
                imageView.setImageResource(R.drawable.cicle_image_sleect);
            imageArray.add(imageView);
            home_bottom_linear.addView(imageView);
        }
        home_viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {

                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                ImageView imageView = new ImageView(getActivity());
                imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                ImageOptions imageOptions = ImageOptions.DEFAULT;
                x.image().bind(imageView, image[position % image.length], imageOptions);
                container.addView(imageView);
                return imageView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((ImageView) object);
            }
        });
        home_viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setImagSrc(position % image.length);
//                Log.d("zzz","Home onPageSelected");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mHandler.sendEmptyMessageDelayed(1, 2000);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //新品
            case R.id.home_xinpin:
//               Toast.makeText(getActivity(),"你好",Toast.LENGTH_SHORT).show();
                break;
            //促销
            case R.id.home_cuxiao:
                break;
            //抢购
            case R.id.home_qianggou:
                tabWidget.setVisibility(View.GONE);
                getActivity().getSupportFragmentManager().beginTransaction().detach(this).hide(this).replace(R.id.tabHost,scareTimeFragment).addToBackStack("home").commit();
                break;
            //推荐
            case R.id.home_tuijian:
                tabWidget.setVisibility(View.GONE);
//                Toast.makeText(getActivity(),"我很好",Toast.LENGTH_SHORT).show();
                getActivity().getSupportFragmentManager().beginTransaction().addToBackStack("home").detach(this).replace(R.id.tabHost,RecomBrandsFragment.newInstance("","")).commit();
                break;
            //热门
            case R.id.home_holder:
                break;
            //输入框
            case R.id.home_editText:

                tabWidget.setVisibility(View.GONE);
                getActivity().getSupportFragmentManager().beginTransaction().detach(this).replace(R.id.tabHost,lookForFragment).addToBackStack("home").commit();
                break;
            //扫描
            case R.id.home_imageView_scan:
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                /**
                 * 打开闪光灯
                 */
                Camera  camera = Camera.open();
                camera.startPreview();
                Camera.Parameters parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                startActivityForResult(intent, 101);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 关闭闪光灯
         */
        CodeUtils.isLightEnable(false);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == 101) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if(result!=null&&result.length()>0){
                        Uri uri=Uri.parse(result);
                        startActivity(new Intent(Intent.ACTION_VIEW,uri));
                    }
                    Toast.makeText(getActivity(), "解析结果:" + result, Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getActivity(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
